Handler
:主要用于将Message
加入到队列MessageQueue
中(按照时间排序),Looper
和MessageQueue
中间的桥梁。
MessageQueue
:Message
消息队列。通过Handler
加入新的Message
,通过Looper
循环不断调用next()
拿出要消费的Message
来触发Handler.dispatchMessage(msg)
然后在回收消费的Message
。
Looper
:通过ThreadLocal
来保证每个线程只有一个Looper
。通过Looper.prepare();
和Looper.loop();
来开启死循环不断取出要消费的Message
。
如下图所示:
Handler.sendMessage() -->sendMessageDelyed()--> MessageQueue.enqueueMessage()
1 | boolean enqueueMessage(Message msg, long when) { |
如下图所示:
Looper.loop()
:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
// 获取线程的 Looper 对象
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
// 获取队列
final MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) { // 死循环不断的获取 消息队列中的消息
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
// 通过 handler 去执行 Message 这个时候就调用了 handleMessage 方法
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
// 回收消息
msg.recycleUnchecked();
}
}
避免handler
引起的内存泄漏问题:调用handler.removeCallbacksAndMessages(null)
清空消息队列,在置handler
为null。因为里面的Message
被引用,所以handler
只让它置为null
是没有用的。
epoll唤醒分析: http://blog.csdn.net/ashqal/article/details/32107099